/**
 * 描述: 数据词典
 * 日期：2019.5.17
 */

(function(KIT, RES) {
  var URL_ROOT = RES.URL_ROOT + "/code",
    URL_FIND = URL_ROOT + "/getCode",
    URL_UPDATE = URL_ROOT + "/updateCode",
    URL_REMOVE = URL_ROOT + "/removeCodes",
    URL_ADD = URL_ROOT + "/addCode",
    URL_CHANGE_STATE = URL_ROOT + "/changeState",
    URL_GET_TREE = URL_ROOT + "/getjsTreeByCode";

  //修改
  var _editInfo = function(e) {
    var __grid = this;

    rapid.confirm("确定要保存吗？", function(yes) {
      if(yes) {
        rapid.post({
          url: URL_UPDATE,
          data: e.serializeJson(),
          success: function(result) {
            e.hide();

            rapid.success("保存成功。", function() {
              __grid.reload();
              _codeTree().refresh();
            }, false);
          }
        });
      }
    });
  };

  //新增
  var _addInfo = function(e) {
    var __grid = this;
    var _pid = rapid("#hidParentid").val();
    rapid.confirm("确定要保存吗？", function(yes) {
      if(yes) {
        rapid.post({
          url: URL_ADD,
          data: rapid.extend(e.serializeJson(), {parentid: _pid}),
          success: function(result) {
            e.hide();

            rapid.success("保存成功。", function() {
              __grid.reload();
              _codeTree().refresh();
            }, false);
          }
        });
      }
    });
  };

  var _codeTree = function(options) {
    if(arguments.length === 1) {
      return $("#treeCode").g_jstree(rapid.nvl(options, {}));
    }
    return $("#treeCode").g_jstree();
  };

  var _getRequestParams = function() {
    var _comSource = rapid("#comLevel").data("comSource");
    var _pid = rapid("#hidParentid").val();
    var codeName = rapid.ui("#txtSearch").val();
    if(rapid("#comLevel").val() == _comSource.AllLV.stringValue) {
      _pid = "";
    }

    return {
      parentId: _pid
    };
  };
  //endregion

  rapid.Page.create("code", {
    render: {
      titleBar: "数据字典管理"
    },
    methods: {
      _getGridmultiActions_: function() {
        var __app = this;

        return [{
          "启用": function() {
            var __this = this;
            var _ids = [];
            var _items = __this.selection();
            for(var i = 0; i < _items.length; i++) {
              _ids.push(_items[i].ui().codeid.val());
            }

            rapid.post({
              url: URL_CHANGE_STATE,
              data: {
                codeids: _ids.toString(),
                state: "1"
              },
              success: function(result) {
                switch(result) {
                  case 0:
                    rapid.success("启用成功！");
                    __this.reload();
                    break;
                  case -1:
                    rapid.warning("要启用的对象存在父级仍被禁用的情况，请先启用父级。");
                    break;
                  default:
                    rapid.error("系统遇到问题。");
                    break;
                }
              }
            });

            return true;
          }
        }, {
          "禁用": function() {
            var __this = this;
            var _ids = [];
            var _items = this.selection();
            for(var i = 0; i < _items.length; i++) {
              _ids.push(_items[i].ui().codeid.val());
            }

            rapid.post({
              url: URL_CHANGE_STATE,
              data: {
                codeids: _ids.toString(),
                state: "0"
              },
              success: function(result) {
                switch(result) {
                  case 0:
                    rapid.success("禁用成功！");
                    __this.reload();
                    break;
                  case -1:
                    rapid.warning("要启用的对象存在父级仍被禁用的情况，请先启用父级。");
                    break;
                  default:
                    rapid.error("系统遇到问题。");
                    break;
                }
              }
            });

            return true;
          }
        }
        ];
      },

      _getGridFields_: function() {
        return [{
          title: "上级", name: "parentname", frozen: true, width: 120

        }, {
          title: "名称", frozen: true, width: 200, action: function(data) {
            return data ? this.action({id: "codename", text: data.codename}) : "";
          }
        }, {
          title: "名称", name: "codename", visible: false, editor: {
            validator: {
              rules: {required: true}
            }
          }
        }, {
          title: "编号", name: "codeid", width: 150
        }, {
          title: "自定义编号", name: "customid", width: 280, editor: true

        }, {
          title: "特殊编号", name: "specialid", width: 280,
          editor: true

        }, {
          title: "状态", name: "enabled", width: 100, formatter: function(value) {
            if(value == "1") {
              return "启用";
            } else if(value == "0") {
              return "禁用";
            } else {
              return "启用";
            }
          }
        }, {
          title: "排序", name: "sortno", width: 100, editor: {
            validator: {
              rules: {
                integer: true,
                min: 1,
                max: 9999
              }
            }
          }
        }, {
          title: "备注", name: "remark", width: 100, editor: true, visible: false
        }];
      },

      _initGridEvent_: function() {
        this.tag("grid")
            .on("beforeAdd", function(dataview) {
              var __grid = this;
              //debugger
              var parentname = rapid("#parentname").val();
              dataview.ui("parentname").val(parentname);
            })
            .on("add", _addInfo)
            .on("update", _editInfo)
            .on("remove", function(ids) {
              var __grid = this;

              rapid.post({
                url: URL_REMOVE,
                data: "codeids=" + ids,
                success: function() {
                  rapid.success("删除成功。", function() {
                    __grid.reload();
                  }, false);
                }
              });
            });

        // 单行点击事件是"click"
      },

      _initGrid_: function() {
        this.tag("grid", rapid("#grd").grid({
          height: "100%",
          addable: true,
          updatable: true,
          removable: true,
          detailed: true,
          history: true,

          dataSource: {
            url: URL_FIND
          },
          pageable: true,
          keyFields: "codeid",
          paramFields: ["id"],
          fields: this._getGridFields_(),
          multiActions: this._getGridmultiActions_()

        }).load({
          data: _getRequestParams()
        }));

        this._initGridEvent_();
      },

      _initUi_: function() {
        var __app = this;

        //查询
        rapid.ui("#txtSearch").on("submit", function() {
          var __value = this.val();
          if(rapid.isEmpty(__value)) {
            if(rapid.nvl(this.tag("search")).length > 0) {
              rapid("#grd").grid().load({
                data: _getRequestParams()
              });
            }

            this.tag("search", "");
            return;
          }

          this.tag("search", __value);

          rapid("#grd").grid().load({
            data: {
              codename: __value
            }
          });
        });
      },
      bindGridEvenet: function() {
        var _app = this;
        rapid("#grd").grid().on("codename", function() {
          var __ui = this.selection()[0].ui();
          var id = __ui.codeid.val();
          var parentname = __ui.codename.val();
          /*    var id = rapid("#grd").grid().selection()[0].ui().codeid.val();
              var parentname = rapid("#grd").grid().selection()[0].ui().codename.val();*/

          rapid("#hidParentid").val(id);
          rapid("#parentname").val(parentname);
          _app.tag("grid").load({
            data: _getRequestParams()
          });
        });

      },
      refresh: function() {
        this.tag("grid").reload();
      },
      //初始化树结构
      bindjsTree: function() {
        var _app = this;
        _codeTree({
          data: {
            url: URL_GET_TREE
          },
          onselected: function(element, inst, node) {
            var _pid = node.id;
            //rapid.ui("#txtSearch").val("");
            rapid("#parentname").val(node.text);
            rapid("#hidParentid").val(node.id);
            //_app._initGrid_();

            rapid("#grd").grid().load({
              data: _getRequestParams()
            });
          }
        });
      },
      /**
       *树结构顶端按钮操作事件
       * */
      bindTreeOpenAndCloseEvent: function() {

        rapid("#btnOpenAllTree").on("click", function() {
          _codeTree().openall();
        });

        rapid("#btnCloseAllTree").on("click", function() {
          _codeTree().closeall();
        });

      }
    }
  })(function() {
    this._initUi_();

    this._initGrid_();

    this.bindGridEvenet();

    this.bindjsTree();

    this.bindTreeOpenAndCloseEvent();

  }).init("index");

})(rapid.kit, rapid.res);




